package cn.qingfeng.a003_chat_v2.server.groupsession;

import cn.qingfeng.a003_chat_v2.server.groupsession.Group;
import cn.qingfeng.a003_chat_v2.server.groupsession.GroupSession;
import cn.qingfeng.a003_chat_v2.server.session.SessionFactory;
import io.netty.channel.Channel;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class GroupSessionMemoryImpl implements GroupSession {
    private final Map<String, Group> groupMap = new ConcurrentHashMap<>();

    @Override
    public cn.qingfeng.a003_chat_v2.server.groupsession.Group createGroup(String groupName, Set<String> members) {
        return groupMap.putIfAbsent(groupName, new Group(groupName, members));
    }

    @Override
    public Set<String> getMembers(String groupName) {
        return groupMap.getOrDefault(groupName, Group.EMPTY_GROUP).getMembers();
    }

    @Override
    public List<Channel> getMembersChannel(String groupName) {
        return getMembers(groupName)
                .stream()
                .filter(Objects::nonNull)
                .map(member -> SessionFactory.getSession().getChannel(member))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

    }

    @Override
    public Group joinMember(String groupName, String member) {
        return groupMap.computeIfPresent(groupName, (key, value) -> {
            value.getMembers().add(member);
            return value;
        });
    }

    @Override
    public Group removeMember(String groupName, String member) {
        return groupMap.computeIfPresent(groupName, (key, value) -> {
            value.getMembers().remove(member);
            return value;
        });
    }
}
